<template>
  <div class="user-change-conf">
    <vx-title-bar current="2" :list="['用户修改录入', '用户修改确认', '用户修改结果']"></vx-title-bar>
    <ui-form ref="content" :model="userForm" label-width="150px" label-position="right" class="vx-form">
      <ui-form-item label="登录ID" prop="loginId">
        {{ userForm.loginId }}
      </ui-form-item>
      <ui-form-item label="用户名" prop="userName">
        {{ userForm.userName }}
      </ui-form-item>
      <ui-form-item label="邮箱" prop="email">
        {{ userForm.email || '--' }}
      </ui-form-item>
      <ui-form-item label="手机号" prop="phone">
        {{ userForm.phone || '--' }}
      </ui-form-item>
      <ui-form-item label="是否启用" prop="enabled">
        {{ $msg('enabledDict')[userForm.enabled] }}
      </ui-form-item>
      <ui-form-item label="是否管理员" prop="adminFlag">
        {{ $msg('adminDict')[userForm.adminFlag] }}
      </ui-form-item>
      <ui-form-item label="角色" v-if="userForm.adminFlag === '0'">
        {{ role.name }}
      </ui-form-item>
      <div class="text-center mg-top-40">
        <ui-button class="default-btn" @click="$router.go(-1)">返回</ui-button>
        <ui-button class="primary-long-btn" @click="submit" :loading="isBtnLoading">确认</ui-button>
      </div>
    </ui-form>
  </div>
</template>

<script>
import userApi from '@/api/user';
export default {
  name: 'user-change-conf',
  data() {
    return {
      userForm: this.getData() || {},
      isBtnLoading: false,
    };
  },
  computed: {
    role() {
      return this.userForm.roleAllList.find((item) => item.id === this.userForm.roleIds);
    },
  },
  methods: {
    /**
     * @description 提交跳转
     */
    async submit() {
      try {
        this.isBtnLoading = true;
        let params = {
          adminFlag: Number(this.userForm.adminFlag),
          id: this.userForm.id,
          enabled: this.userForm.enabled,
          phone: this.userForm.phone,
          email: this.userForm.email,
          userName: this.userForm.userName,
        };
        const res = await userApi.userEdit(params);
        //不是管理员才需要发此接口
        if (this.userForm.adminFlag === '0') {
          await userApi.userAddRole({ userId: this.userForm.id, roleIds: this.role.id });
        }
        this.setData({ res: res });
        this.$router.replace({ path: '/system/user/userChangeRes' });
      } finally {
        this.isBtnLoading = false;
      }
    },
  },
  /**
   * @description 跳转的页面不是结果页和录入页清除数据
   */
  beforeRouteLeave(to, from, next) {
    if (to.path !== '/system/user/userChangeRes' && to.path !== '/system/user/userChangePre') {
      this.clearData();
    }
    next();
  },
};
</script>
